package com.wu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author wuyanshen
 * @date 2019-01-14 5:32 PM
 * @discription JWT工具类
 */
public class JwtUtilOne {

    // 过期时间5分钟
    private static final long EXPIRE_TIME = 30*60*1000;

    /**
     * 校验token是否正确
     * @param token 密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     * @param username 用户名
     * @param secret 用户的密码
     * @return 加密的token
     */
    public static String sign(String username, String secret) {
        try {
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            System.out.println("algorithm= "+algorithm);
            // 附带username信息
            return JWT.create()
                    .withIssuer("auth0")
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String userName = "admin";
        String secret = "c41d7c66e1b8404545aa3a0ece2006ac";
//        String token = sign(userName,secret);
//        System.out.println(token);

        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTU0NzYzNTk5NCwidXNlcm5hbWUiOiJhZG1pbiJ9.0LXuOZDDdih85iL5rLtTsZdnHhR_mouPBuutCVNz9fM";
//        String userName = getUsername(token);
//        System.out.println("用户名:"+userName);

        boolean flag = verify(token, userName, secret);
        if (flag) {
            System.out.println("正确");
        } else {
            System.out.println("错误");
        }


    }
}
